package com.example.pei.ithinklearnt.present;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.view.activity.Login_Activity;
import com.example.pei.ithinklearnt.view.activity.RegisterOneActivity;
import com.example.pei.ithinklearnt.view.interfaces.LoginInterface;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by Pei on 2017/12/5.
 */

public class LoginPresentImp implements LoginPresent {
    private LoginInterface loginInterface;
    private UserInfo user;

    public LoginPresentImp(LoginInterface loginInterface){
        this.loginInterface=loginInterface;
    }

    @Override
    public void loginClick() {
        loginInterface.setLoginClickabel(false,false);   //设置不可点击登录
        user=new UserInfo();
        user.setUsername(loginInterface.getUserName());
        user.setPassword(loginInterface.getPassWord());
        user.login(new SaveListener<UserInfo>() {
            @Override
            public void done(UserInfo bmobUser, BmobException e) {
                loginInterface.setLoginClickabel(true,false);   //设置可点击登录
                loginInterface.setEditViewEnable(true);  //可以修改文本框内容了 （一般是用户名密码错误
                if(e==null){
                    getCurrentUser();
                    loginInterface.setLoginProgress(100);
                }else if(e.getErrorCode()==9016){
                    Toast.makeText(loginInterface.getActivity(),"网络跑丢了...",Toast.LENGTH_SHORT).show();
                    loginInterface.setLoginProgress(-1);
                }else if(e.getErrorCode()==101){
                    Toast.makeText(loginInterface.getActivity(),"用户名或者密码错误",Toast.LENGTH_SHORT).show();
                    loginInterface.setLoginProgress(-1);
                }else{
                    Toast.makeText(loginInterface.getActivity(),"登录失败",Toast.LENGTH_SHORT).show();
                    loginInterface.setLoginProgress(-1);
                }
            }
        });

    }

    @Override
    public void registeClick() {
        Intent intent=new Intent(loginInterface.getActivity(), RegisterOneActivity.class);
        loginInterface.getActivity().startActivity(intent);
    }

    @Override
    public void getCurrentUser() {
        user = UserInfo.getCurrentUser(UserInfo.class);

        if(user != null){
            // 允许用户使用应用
            AppApplication.setCurrentUser(user);
            Intent intent=new Intent("main_Activity");
            Bundle bundle=new Bundle();
            bundle.putParcelable("currentUser", user);
            intent.putExtras(bundle);
            loginInterface.getActivity().startActivity(intent);

            //销毁登录活动
            loginInterface.getActivity().finish();

        }else{
            //缓存用户对象为空时， 可打开用户注册界面…
        }
    }
}
